
#include "mse_loss_grad_tiling.h"
#include "register/op_def_registry.h"

namespace optiling
{
static ge::graphStatus TilingFunc(gert::TilingContext *context)
{
    MseLossGradTilingData tiling;

    set_size_by_input(tiling, context, 0);

    auto predict_size = context->GetInputShape(0)->GetStorageShape().GetShapeSize();
    auto dout_size = context->GetInputShape(2)->GetStorageShape().GetShapeSize();
    tiling.set_doutSameShape(predict_size == dout_size);

    auto runtime_attrs = context->GetAttrs();
    auto attr0 = runtime_attrs->GetStr(0);
    if (strncmp(attr0, "mean", 4) == 0)
    {
        tiling.set_tag(0);
    }
    else if (strncmp(attr0, "sum", 3) == 0)
    {
        tiling.set_tag(1);
    }
    else if (strncmp(attr0, "none", 4) == 0)
    {
        tiling.set_tag(2);
    }
    else
    {
        tiling.set_tag(0);
    }

    CommonTiling<MseLossGradTilingData> commonTiling;
    commonTiling.tiling = &tiling;
    commonTiling.context = context;
    commonTiling.data_size = tiling.get_size();
    commonTiling.vector_align_size = 32;
    commonTiling.input_arg_count = 3;
    commonTiling.output_arg_count = 1;
    commonTiling.apply();

    tiling_save_to_buffer(tiling, context);
    tiling_zero_workspace(context);

    return ge::GRAPH_SUCCESS;
}
} // namespace optiling

namespace ge
{
static ge::graphStatus InferShape(gert::InferShapeContext *context)
{
    const gert::Shape *x1_shape = context->GetInputShape(0);
    gert::Shape *y_shape = context->GetOutputShape(0);
    *y_shape = *x1_shape;
    return GRAPH_SUCCESS;
}
} // namespace ge

namespace ops
{
class MseLossGrad : public OpDef
{
  public:
    explicit MseLossGrad(const char *name) : OpDef(name)
    {
        this->Input("predict")
            .ParamType(REQUIRED)
            .DataType({ge::DT_FLOAT, ge::DT_FLOAT16})
            .Format({ge::FORMAT_ND, ge::FORMAT_ND})
            .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});
        this->Input("label")
            .ParamType(REQUIRED)
            .DataType({ge::DT_FLOAT, ge::DT_FLOAT16})
            .Format({ge::FORMAT_ND, ge::FORMAT_ND})
            .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});
        this->Input("dout")
            .ParamType(REQUIRED)
            .DataType({ge::DT_FLOAT, ge::DT_FLOAT16})
            .Format({ge::FORMAT_ND, ge::FORMAT_ND})
            .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});
        this->Output("y")
            .ParamType(REQUIRED)
            .DataType({ge::DT_FLOAT, ge::DT_FLOAT16})
            .Format({ge::FORMAT_ND, ge::FORMAT_ND})
            .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});
        this->Attr("reduction").AttrType(OPTIONAL).String("mean");

        this->SetInferShape(ge::InferShape);

        this->AICore().SetTiling(optiling::TilingFunc);
        this->AICore().AddConfig("ascend310b");
    }
};

OP_ADD(MseLossGrad);
} // namespace ops
